import React, { useCallback, useMemo } from 'react';
import { Checkbox } from 'antd';
import PropTypes from 'prop-types';

const CheckboxCell = ({ allRows, record, selectedRows, dispatch, dispatchType, connectRecordFilter }) => {
    const onChange = useCallback(
        event => {
            const { checked } = event.target;
            let connectRecords = [];

            if (connectRecordFilter) {
                connectRecords = allRows.filter(item => connectRecordFilter(item, record)) || [];
            }

            dispatch({
                type: dispatchType,
                payload: {
                    checked,
                    rows: [].concat(record).concat(connectRecords)
                }
            });
        },
        [allRows, record, dispatchType, dispatch]
    );
    const checked = useMemo(() => !!selectedRows.find(item => item.id === record.id), [selectedRows, record]);
    return <Checkbox value={record.id} onChange={onChange} checked={checked} />;
};

CheckboxCell.propTypes = {
    allRows: PropTypes.array,
    record: PropTypes.object,
    selectedRows: PropTypes.array,
    dispatchType: PropTypes.string,
    connectRecordFilter: PropTypes.func
};

CheckboxCell.defaultProps = {
    allRows: [],
    record: null,
    selectedRows: [],
    dispatchType: {},
    connectRecordFilter: null
};

const CheckBoxTitle = ({ allRows, selectedRows, dispatch, dispatchType }) => {
    const onChange = useCallback(
        event => {
            const { checked } = event.target;
            dispatch({
                type: dispatchType,
                payload: checked ? allRows : []
            });
        },
        [allRows]
    );

    const indeterminate = useMemo(
        () => allRows.length > 0 && selectedRows.length > 0 && allRows.length > selectedRows.length,
        [allRows, selectedRows]
    );

    const checked = useMemo(() => allRows.length === selectedRows.length && selectedRows.length > 0, [
        allRows,
        selectedRows
    ]);

    return <Checkbox indeterminate={indeterminate} checked={checked} onChange={onChange} />;
};

export default CheckboxCell;
export { CheckBoxTitle };
